package cn.geodata.dataview;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.geotools.data.DataStore;
import org.geotools.data.FeatureSource;
import org.geotools.data.FeatureStore;
import org.geotools.data.Query;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.factory.FactoryConfigurationError;
import org.geotools.factory.GeoTools;
import org.geotools.feature.AttributeType;
import org.geotools.feature.AttributeTypeFactory;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureType;
import org.geotools.feature.FeatureTypeBuilder;
import org.geotools.feature.SchemaException;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.expression.Expression;

import cn.geodata.database.DataObject;
import cn.geodata.dataview.util.Util;

import com.sun.net.httpserver.Filter;
import com.vividsolutions.jts.geom.MultiPolygon;

public class FireStatistic {
	private static Logger Log = Logger.getLogger(FireStatistic.class);
	
	public FeatureCollection queryByPathAndRow(int path, int row) throws IOException, URISyntaxException{
		FeatureSource _fs = this.getFeatureSource();
		FilterFactory2 _filterFactory = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
		Filter _filter = (Filter) _filterFactory.add(
					(Expression)_filterFactory.equal(_filterFactory.property("path"), _filterFactory.literal(path)), 
					(Expression)_filterFactory.equal(_filterFactory.property("row"), _filterFactory.literal(row))
				);
		
		return _fs.getFeatures((Query) _filter);
	}
	
	public File getStatisticDataset() throws IOException {
		return new File(Util.getSpatialDataRepo(), this.getStatisticFileName());
	}
	
	public String getStatisticFileName() throws IOException {
		return Util.getConfigure().getProperty("dataset.statistic");
	}
	
	public FeatureType createFeatureType() throws FactoryConfigurationError, SchemaException, IOException {
		AttributeTypeFactory _attribFeatory = CommonFactoryFinder.getAttributeTypeFactory(GeoTools.getDefaultHints());
		FeatureTypeBuilder _featureFactory = CommonFactoryFinder.getFeatureTypeFactory(GeoTools.getDefaultHints());
		
		ArrayList<AttributeType> _attrs = new ArrayList<AttributeType>();
		_attrs.add(_attribFeatory.newAttributeType("shape", MultiPolygon.class));
		_attrs.add(_attribFeatory.newAttributeType("path", Integer.class));
		_attrs.add(_attribFeatory.newAttributeType("row", Integer.class));
		_attrs.add(_attribFeatory.newAttributeType("count", Integer.class));
		
		return _featureFactory.newFeatureType((AttributeType[])_attrs.toArray(new AttributeType[0]), this.getStatisticFileName());
	}
	
	public FeatureSource createEmptyFeatureSource() throws IOException, FactoryConfigurationError, SchemaException, URISyntaxException {
		DataStore _dataStore = this.createEmptyDataStore();
		_dataStore.createSchema(this.createFeatureType());
		
		return _dataStore.getFeatureSource(this.getStatisticFileName());
	}
	
	public DataStore createEmptyDataStore() throws IOException, URISyntaxException {
		ShapefileDataStoreFactory _factory = new ShapefileDataStoreFactory();
		
		Log.info("URLP:" + ShapefileDataStoreFactory.URLP.type.toString());
		Map _param = new HashMap();
		_param.put(ShapefileDataStoreFactory.NAMESPACEP.key, new URI("http://www.geodata.cn/dataview"));
		_param.put(ShapefileDataStoreFactory.URLP.key, this.getStatisticDataset().toURL());
		
		return _factory.createNewDataStore(_param);
	}

	public FeatureSource getFeatureSource() throws IOException, URISyntaxException {
		ShapefileDataStoreFactory _factory = new ShapefileDataStoreFactory();
		
		Log.info("URLP:" + ShapefileDataStoreFactory.URLP.type.toString());
		Map _param = new HashMap();
		_param.put(ShapefileDataStoreFactory.NAMESPACEP.key, new URI("http://www.geodata.cn/dataview"));
		_param.put(ShapefileDataStoreFactory.URLP.key, this.getStatisticDataset().toURL());
		
		return _factory.createDataStore(_param).getFeatureSource(this.getStatisticFileName());
	}
	
	public void build() throws Exception {
		FeatureStore _featureSource = (FeatureStore)this.createEmptyFeatureSource();
		FeatureType _featureType = _featureSource.getSchema();
		
		Map<String, Integer> _count = new HashMap<String, Integer>();
		
		ArrayList<DataObject> _fires = (new FireFactory()).list();
		for(DataObject _o : _fires){
			Fire _fire = (Fire)_o;
			String _id = _fire.getPath() + "," + _fire.getRow();
			if(_count.containsKey(_id)){
				_count.put(_id, _count.get(_id) + 1);
			}
			else{
				_count.put(_id, 1);
			}
		}
		
		FeatureCollection _fs = CommonFactoryFinder.getFeatureCollections(GeoTools.getDefaultHints()).newCollection();
		for(String _key : _count.keySet()){
			Log.info("Key:" + _key + "," + _count.get(_key));
			String[] _items = _key.split(",");

			int _path = Integer.parseInt(_items[0]);
			int _row = Integer.parseInt(_items[1]);
			
			Feature _f = Util.locatePathRow(_path, _row);
			Feature _n = _featureType.create(new Object[]{_f.getDefaultGeometry(), _path, _row, _count.get(_key)});
			
			_fs.add(_n);
		}
		
		_featureSource.addFeatures(_fs);
	}
}
